﻿using DGSFramework;
using DGSFramework.Models;
using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace Framework.Resources
{
    /// <summary>
    /// Summary description for GetStockList
    /// </summary>
    public class GetStockList : IHttpHandler
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            var status = 0;
            var stockList = new List<StockDataModel>();
            var pageSize = 50;
            var pageIndex = 1;
            var totalRecord = 0;
            var code = string.Empty;
            try
            {
                var type = HttpContext.Current.Request.Form["type"].ToString();
                if (HttpContext.Current.Request.Form["code"] != null)
                    code = HttpContext.Current.Request.Form["code"].ToString();
                type = type.ToLower();
                if (HttpContext.Current.Request.Form["page"] != null)
                    pageIndex = int.Parse(HttpContext.Current.Request.Form["page"].ToString());
                //var currentDate = Globals.DateGetData();
                var currentDate = entity.dgs_StockDatas.Max(d => d.GetTime);                
                if (!string.IsNullOrEmpty(code)) //search
                {
                    stockList = entity.dgs_Stocks.Where(d => d.Code.ToLower().Contains(code) && d.IsDelete == false).Select(d => new StockDataModel
                     {
                         Code = d.Code,
                         GetTime = currentDate,
                         Name = d.Name,
                         Name_en = d.Name_en,
                         Sector = d.Type,
                         Sector_en = d.Type_en
                     }).ToList();

                    var stockData = entity.dgs_StockDatas.Where(d => d.dgs_Stocks.Code.ToLower().Contains(code) && d.GetTime == currentDate).Select(d => new StockDataModel
                    {
                        GetTime = d.GetTime,
                        GiaThamChieu = d.GiaThamChieu,
                        Cao = d.Cao,
                        Thap = d.Thap,
                        KL_KL = d.KL_KL,
                        KL_Gia = d.KL_Gia,
                        Code = d.dgs_Stocks.Code,
                        GiaMoCua = d.GiaMoCua,
                        BT = d.BT,
                        ST = d.ST,
                        DB_Gia1 = d.DB_Gia1,
                        DM_Gia1 = d.DM_Gia1
                    }).ToList();

                    foreach (var item in stockList)
                    {
                        var stockDataItem = stockData.Where(d => d.Code == item.Code).SingleOrDefault();
                        if (stockDataItem != null)
                        {
                            item.GiaThamChieu = stockDataItem.GiaThamChieu;
                            item.Cao = stockDataItem.Cao;
                            item.Thap = stockDataItem.Thap;
                            item.KL_KL = stockDataItem.KL_KL;
                            item.KL_Gia = stockDataItem.KL_Gia;
                            item.GiaMoCua = stockDataItem.GiaMoCua;
                            item.BT = stockDataItem.BT;
                            item.ST = stockDataItem.ST;
                            item.DB_Gia1 = stockDataItem.DB_Gia1;
                            item.DM_Gia1 = stockDataItem.DM_Gia1;
                        }
                    }
                    status = 1;
                    totalRecord = 50;
                }
                else if (type == "allstock")
                {
                    totalRecord = entity.dgs_Stocks.Where(d => d.IsDelete == false).Count();
                    stockList = entity.dgs_Stocks.Where(d => d.IsDelete == false).OrderBy(d => d.Code).Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(d => new StockDataModel
                    {
                        Code = d.Code,
                        GetTime = currentDate,
                        Name = d.Name,
                        Name_en = d.Name_en,
                        Sector = d.Type,
                        Sector_en = d.Type_en
                    }).ToList();

                    var stockData = entity.dgs_StockDatas.Where(d => d.GetTime == currentDate).Select(d => new StockDataModel
                    {
                        GetTime = d.GetTime,
                        GiaThamChieu = d.GiaThamChieu,
                        Cao = d.Cao,
                        Thap = d.Thap,
                        KL_KL = d.KL_KL,
                        KL_Gia = d.KL_Gia,
                        Code = d.dgs_Stocks.Code,
                        GiaMoCua = d.GiaMoCua,
                        BT = d.BT,
                        ST = d.ST,
                        DB_Gia1 = d.DB_Gia1,
                        DM_Gia1 = d.DM_Gia1
                    }).ToList();

                    foreach (var item in stockList)
                    {
                        var stockDataItem = stockData.Where(d => d.Code == item.Code).SingleOrDefault();
                        if (stockDataItem != null)
                        {
                            item.GiaThamChieu = stockDataItem.GiaThamChieu;
                            item.Cao = stockDataItem.Cao;
                            item.Thap = stockDataItem.Thap;
                            item.KL_KL = stockDataItem.KL_KL;
                            item.KL_Gia = stockDataItem.KL_Gia;
                            item.GiaMoCua = stockDataItem.GiaMoCua;
                            item.BT = stockDataItem.BT;
                            item.ST = stockDataItem.ST;
                            item.DM_Gia1 = stockDataItem.DM_Gia1;
                            item.DB_Gia1 = stockDataItem.DB_Gia1;
                        }
                    }
                    status = 1;
                }
                else if (type == "topvolume")
                {
                    totalRecord = 100;
                    stockList = entity.dgs_StockDatas.Where(d => d.GetTime == currentDate && d.dgs_Stocks.IsDelete == false).OrderByDescending(d => d.TongKL).Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(d => new StockDataModel
                    {
                        GetTime = d.GetTime,
                        GiaThamChieu = d.GiaThamChieu,
                        Cao = d.Cao,
                        Thap = d.Thap,
                        KL_KL = d.KL_KL,
                        KL_Gia = d.KL_Gia,
                        Code = d.dgs_Stocks.Code,
                        Name = d.dgs_Stocks.Name,
                        Name_en = d.dgs_Stocks.Name_en,
                        Sector = d.dgs_Stocks.Type,
                        Sector_en = d.dgs_Stocks.Type_en,
                        GiaMoCua = d.GiaMoCua,
                        BT = d.BT,
                        ST = d.ST,
                        DB_Gia1 = d.DB_Gia1,
                        DM_Gia1 = d.DM_Gia1
                    }).ToList();
                    status = 1;
                }
                else if (type == "topgainer")
                {
                    totalRecord = 100;
                    stockList = entity.dgs_StockDatas.Where(d => d.GetTime == currentDate && d.dgs_Stocks.IsDelete == false).OrderByDescending(d => (d.Cao / d.GiaThamChieu - 1) * 100).Skip(0).Take(50).Select(d => new StockDataModel
                    {
                        GetTime = d.GetTime,
                        GiaThamChieu = d.GiaThamChieu,
                        Cao = d.Cao,
                        Thap = d.Thap,
                        KL_KL = d.KL_KL,
                        KL_Gia = d.KL_Gia,
                        Code = d.dgs_Stocks.Code,
                        Name = d.dgs_Stocks.Name,
                        Name_en = d.dgs_Stocks.Name_en,
                        Sector = d.dgs_Stocks.Type,
                        Sector_en = d.dgs_Stocks.Type_en,
                        GiaMoCua = d.GiaMoCua,
                        BT = d.BT,
                        ST = d.ST,
                        DB_Gia1 = d.DB_Gia1,
                        DM_Gia1 = d.DM_Gia1
                    }).ToList();
                    status = 1;
                }
                else if (type == "toploser")
                {
                    totalRecord = 100;
                    stockList = entity.dgs_StockDatas.Where(d => d.GetTime == currentDate && d.dgs_Stocks.IsDelete == false).OrderByDescending(d => (d.Thap / d.GiaThamChieu - 1) * 100).Skip(0).Take(50).Select(d => new StockDataModel
                    {
                        GetTime = d.GetTime,
                        GiaThamChieu = d.GiaThamChieu,
                        Cao = d.Cao,
                        Thap = d.Thap,
                        KL_KL = d.KL_KL,
                        KL_Gia = d.KL_Gia,
                        Code = d.dgs_Stocks.Code,
                        Name = d.dgs_Stocks.Name,
                        Name_en = d.dgs_Stocks.Name_en,
                        Sector = d.dgs_Stocks.Type,
                        Sector_en = d.dgs_Stocks.Type_en,
                        GiaMoCua = d.GiaMoCua,
                        BT = d.BT,
                        ST = d.ST,
                        DB_Gia1 = d.DB_Gia1,
                        DM_Gia1 = d.DM_Gia1
                    }).ToList();
                    status = 1;
                }
                else if (type == "rsi30")
                {
                    //var entityConn = entity.Connection as EntityConnection;
                    //var dbConn = entityConn.StoreConnection as SqlConnection;
                    //dbConn.Open();
                    //var sqlQuery = string.Format("EXEC GetRSI30 @DateTo = N'{0}'", currentDate.ToString("MM/dd/yyyy"));
                    //var cmd = new SqlCommand(sqlQuery, dbConn);
                    //var lstReturn = new List<RSIModel>();
                    //using (var reader = cmd.ExecuteReader())
                    //{
                    //    while (reader.Read())
                    //    {
                    //        var item = new RSIModel();
                    //        item.StockId = int.Parse(reader["StockId"].ToString());
                    //        item.StockDataID = int.Parse(reader["StockDataID"].ToString());
                    //        item.GetTime = DateTime.Parse(reader["GetTime"].ToString());
                    //        item.GiaThamChieu = float.Parse(reader["GiaThamChieu"].ToString());
                    //        if (!string.IsNullOrEmpty(reader["Change"].ToString()))
                    //            item.Change = float.Parse(reader["Change"].ToString());
                    //        if (!string.IsNullOrEmpty(reader["Gain"].ToString()))
                    //            item.Gain = float.Parse(reader["Gain"].ToString());
                    //        if (!string.IsNullOrEmpty(reader["Loss"].ToString()))
                    //            item.Loss = float.Parse(reader["Loss"].ToString());
                    //        if (!string.IsNullOrEmpty(reader["AvgGain"].ToString()))
                    //            item.AvgGain = float.Parse(reader["AvgGain"].ToString());
                    //        if (!string.IsNullOrEmpty(reader["AvgLoss"].ToString()))
                    //            item.AvgLoss = float.Parse(reader["AvgLoss"].ToString());
                    //        if (!string.IsNullOrEmpty(reader["RSI"].ToString()))
                    //            item.RSI = float.Parse(reader["RSI"].ToString());
                    //        lstReturn.Add(item);
                    //    }
                    //}
                    //dbConn.Close();
                    //lstReturn = lstReturn.Where(d => d.RSI <= 30).ToList();
                    //foreach (var item in lstReturn)
                    //{
                    //    stockList.Add(new StockDataModel { Code = item.StockId.ToString() });
                    //}
                    //status = 1;
                }
                else if (type == "so20")
                {

                }
                else if (type == "watchlistbuy")
                {
                    var lstStock = entity.dgs_Stocks.Where(d => d.IsWatchListBuy == true && d.IsDelete == false);
                    stockList = lstStock.OrderBy(d => d.Code).Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(d => new StockDataModel
                    {
                        Code = d.Code,
                        Name = d.Name,
                        Name_en = d.Name_en,
                        GetTime = currentDate,
                        Sector = d.Type,
                        Sector_en = d.Type_en
                    }).ToList();

                    var stockData = entity.dgs_StockDatas.Where(d => d.GetTime == currentDate).Select(d => new StockDataModel
                    {
                        GetTime = d.GetTime,
                        GiaThamChieu = d.GiaThamChieu,
                        Cao = d.Cao,
                        Thap = d.Thap,
                        KL_KL = d.KL_KL,
                        KL_Gia = d.KL_Gia,
                        Code = d.dgs_Stocks.Code,
                        GiaMoCua = d.GiaMoCua,
                        BT = d.BT,
                        ST = d.ST,
                        DB_Gia1 = d.DB_Gia1,
                        DB_Gia2 = d.DB_Gia2,
                        DM_Gia1 = d.DM_Gia1,
                        DM_Gia2 = d.DM_Gia2
                    }).ToList();

                    foreach (var item in stockList)
                    {
                        var stockDataItem = stockData.Where(d => d.Code.ToLower() == item.Code.ToLower()).SingleOrDefault();
                        if (stockDataItem != null)
                        {
                            item.GiaThamChieu = stockDataItem.GiaThamChieu;
                            item.Cao = stockDataItem.Cao;
                            item.Thap = stockDataItem.Thap;
                            item.KL_KL = stockDataItem.KL_KL;
                            item.KL_Gia = stockDataItem.KL_Gia;
                            item.GiaMoCua = stockDataItem.GiaMoCua;
                            item.BT = stockDataItem.BT;
                            item.ST = stockDataItem.ST;
                            item.DB_Gia1 = stockDataItem.DB_Gia1;
                            item.DB_Gia2 = stockDataItem.DB_Gia2;
                            item.DM_Gia1 = stockDataItem.DM_Gia1;
                            item.DM_Gia2 = stockDataItem.DM_Gia2;
                        }
                    }
                    status = 1;
                    totalRecord = lstStock.Count();
                }
                else if (type == "watchlistsell")
                {
                    var lstStock = entity.dgs_Stocks.Where(d => d.IsWatchListSell == true && d.IsDelete == false);
                    stockList = lstStock.OrderBy(d => d.Code).Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(d => new StockDataModel
                    {
                        Code = d.Code,
                        Name = d.Name,
                        Name_en = d.Name_en,
                        GetTime = currentDate,
                        Sector = d.Type,
                        Sector_en = d.Type_en
                    }).ToList();

                    var stockData = entity.dgs_StockDatas.Where(d => d.GetTime == currentDate).Select(d => new StockDataModel
                    {
                        GetTime = d.GetTime,
                        GiaThamChieu = d.GiaThamChieu,
                        Cao = d.Cao,
                        Thap = d.Thap,
                        KL_KL = d.KL_KL,
                        KL_Gia = d.KL_Gia,
                        Code = d.dgs_Stocks.Code,
                        GiaMoCua = d.GiaMoCua,
                        BT = d.BT,
                        ST = d.ST,
                        DB_Gia1 = d.DB_Gia1,
                        DB_Gia2 = d.DB_Gia2,
                        DM_Gia1 = d.DM_Gia1,
                        DM_Gia2 = d.DM_Gia2
                    }).ToList();

                    foreach (var item in stockList)
                    {
                        var stockDataItem = stockData.Where(d => d.Code.ToLower() == item.Code.ToLower()).SingleOrDefault();
                        if (stockDataItem != null)
                        {
                            item.GiaThamChieu = stockDataItem.GiaThamChieu;
                            item.Cao = stockDataItem.Cao;
                            item.Thap = stockDataItem.Thap;
                            item.KL_KL = stockDataItem.KL_KL;
                            item.KL_Gia = stockDataItem.KL_Gia;
                            item.GiaMoCua = stockDataItem.GiaMoCua;
                            item.BT = stockDataItem.BT;
                            item.ST = stockDataItem.ST;
                            item.DM_Gia1 = stockDataItem.DM_Gia1;
                            item.DM_Gia2 = stockDataItem.DM_Gia2;
                            item.DB_Gia1 = stockDataItem.DB_Gia1;
                            item.DB_Gia2 = stockDataItem.DB_Gia2;
                        }
                    }
                    status = 1;
                    totalRecord = lstStock.Count();
                }
                else if (type == "topactive")
                {
                    var lstStock = entity.dgs_StockDatas.Where(d => d.GetTime == currentDate && (d.BT > 0 || d.ST > 0) && d.dgs_Stocks.IsDelete == false);
                    stockList = lstStock.OrderByDescending(d => (d.BT + d.ST)).Skip(0).Take(50).Select(d => new StockDataModel
                    {
                        GetTime = d.GetTime,
                        GiaThamChieu = d.GiaThamChieu,
                        Cao = d.Cao,
                        Thap = d.Thap,
                        KL_KL = d.KL_KL,
                        KL_Gia = d.KL_Gia,
                        Code = d.dgs_Stocks.Code,
                        GiaMoCua = d.GiaMoCua,
                        BT = d.BT,
                        ST = d.ST,
                        Sector = d.dgs_Stocks.Type,
                        Sector_en = d.dgs_Stocks.Type_en,
                        DB_Gia1 = d.DB_Gia1,
                        DM_Gia1 = d.DM_Gia1,
                        Name = d.dgs_Stocks.Name,
                        Name_en = d.dgs_Stocks.Name_en,
                    }).ToList();
                    var stockCount = lstStock.Count();
                    if (stockCount > 50)
                        totalRecord = 100;
                    else
                        totalRecord = 50;
                    status = 1;
                }
                else
                {
                    var isFavorite = type.IndexOf('_');
                    if (isFavorite > 1)
                    {
                        var favorite = type.Split('_');
                        if (favorite.Length > 1)
                        {
                            var favoriteID = int.Parse(favorite[1]);
                            var favoriteDetailList = entity.dgs_FavoriteDetails.Where(d => d.dgs_Favorite.FavID == favoriteID && d.dgs_Stocks.IsDelete == false);
                            stockList = favoriteDetailList.OrderByDescending(d => d.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(d => new StockDataModel
                            {
                                Code = d.dgs_Stocks.Code,
                                Name = d.dgs_Stocks.Name,
                                Name_en = d.dgs_Stocks.Name_en,
                                GetTime = currentDate,
                                Sector = d.dgs_Stocks.Type,
                                Sector_en = d.dgs_Stocks.Type_en
                            }).ToList();
                            var stockData = entity.dgs_StockDatas.Where(d => d.GetTime == currentDate).Select(d => new StockDataModel
                            {
                                GetTime = d.GetTime,
                                GiaThamChieu = d.GiaThamChieu,
                                Cao = d.Cao,
                                Thap = d.Thap,
                                KL_KL = d.KL_KL,
                                KL_Gia = d.KL_Gia,
                                Code = d.dgs_Stocks.Code,
                                GiaMoCua = d.GiaMoCua,
                                BT = d.BT,
                                ST = d.ST,
                                DB_Gia1 = d.DB_Gia1,
                                DM_Gia1 = d.DM_Gia1
                            }).ToList();
                            foreach (var item in stockList)
                            {
                                var stockDataItem = stockData.Where(d => d.Code.ToLower() == item.Code.ToLower()).SingleOrDefault();
                                if (stockDataItem != null)
                                {
                                    item.GiaThamChieu = stockDataItem.GiaThamChieu;
                                    item.Cao = stockDataItem.Cao;
                                    item.Thap = stockDataItem.Thap;
                                    item.KL_KL = stockDataItem.KL_KL;
                                    item.KL_Gia = stockDataItem.KL_Gia;
                                    item.GiaMoCua = stockDataItem.GiaMoCua;
                                    item.BT = stockDataItem.BT;
                                    item.ST = stockDataItem.ST;
                                    item.DM_Gia1 = stockDataItem.DM_Gia1;
                                    item.DB_Gia1 = stockDataItem.DB_Gia1;
                                }
                            }
                            status = 1;
                            totalRecord = favoriteDetailList.Count();
                        }

                    }
                }


            }
            catch (Exception ex)
            {
                status = -1;
            }
            context.Response.Write(
                    jsonSerializer.Serialize(
                        new
                        {
                            Status = status,
                            TotalRecord = totalRecord,
                            Data = stockList
                        }
                    )
                );
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}